﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : CRD
/// 계      층 : Presentation Layer
/// 프로그램명 : Crd4010b
/// 파  일  명 : Crd4010b.aspx.cs
/// 설      명 : 카드결제대금검증
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2011-03-03 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework;
using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Crd.Exe;


namespace Updms.Crd
{
	public partial class Crd4010b : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Crd4010b";
		public static readonly string gs_path_info = "/updms/Crd/" + PID + ".aspx";

		Global global = new Global();

		// 페이지모드
		private string gs_page_mode = "";

		OleDbConnection con;
		protected string gs_source = FILE_PATH_UPLOAD_EXCEL_BATCH + PID + "_template.xls";

		//검색
		protected string kw1 = "";	// card_cd
		protected string kw2 = "";	// paymnt_dt

		//합계
		decimal ld_amount_card = 0;
		decimal ld_amount_updms = 0;

		#endregion

		#region Page_Load

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
				SetSearchParameter();
				SetCardInfo();
			}
		}		

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region SetSearchParameter

		//검색파라미터
		private void SetSearchParameter()
		{
			if (!String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
			{
				kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
			}
			if (!String.IsNullOrEmpty(Request.QueryString["kw2"])) // url에 값이 없으면
			{
				kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
			}
		}

		#endregion

		#region 마스터 Method (SetCardInfo)

		private void SetCardInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//카드정보(이미지)
			using (Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT())
			{
				lo_ds.Merge(_Crd1010m_NT.GetCardInfo(lo_dp));
			}

			string ls_card_image = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "Attach_File1");
			img_card_image.Src = FILE_PATH_UPLOAD_WEB_PATH + (string.IsNullOrEmpty(ls_card_image) ? "empty.png" : ls_card_image);

			lbl_card_nm.Text = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CRD_INFO", "CARD_NM");
			lbl_paymnt_dt.Text = kw2;
		}

		#endregion

		#region CRUD (SelectProcess, ConfirmProcess, InsertProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_paymnt_dt", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			
			OleDbDataAdapter adapter;

			if (FileUtil.IsFileExist(gs_source))
			{
				try
				{
					string connStr = @"provider=Microsoft.ACE.OLEDB.12.0;data source=" + gs_source + ";Extended Properties=Excel 12.0;";
					con = new OleDbConnection(connStr);
					con.Open();

					string query_card = "SELECT * FROM [CARD_DATA_" + kw1 + "$]";
					adapter = new OleDbDataAdapter(query_card, con);
					adapter.Fill(lo_ds, "CARD_DATA");

					using (Crd4010b_NT _Crd4010b_NT = new Crd4010b_NT())
					{
						lo_ds.Merge(_Crd4010b_NT.GetListForVerify(lo_dp));
					}

					gs_page_mode = DataSetUtil.CheckRowCount(lo_ds, "CARD_DATA") ? DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CRD_BATCH") ? "R" : "N" : "N";

					//카드사
					GridView1.DataSource = lo_ds.Tables["CARD_DATA"];
					GridView1.DataBind();

					//UPDMS
					GridView2.DataSource = lo_ds.Tables["UPDMS_CRD_BATCH"];
					GridView2.DataBind();
				}
				catch (OleDbException oe)
				{
					SMEventLog.WriteExceptionLog(oe);
					CallExceptionMsgBoxInAjax(oe);
				}
				catch (Exception e)
				{
					SMEventLog.WriteExceptionLog(e);
				}
				finally
				{
					con.Close();
				}
			}
			else
			{
				gs_page_mode = "";
				CallMsgBoxInAjax("MSG_ERR_126");	// 템플릿 파일이 없습니다
			}
		}

		//확정
		private void ConfirmProcess(string ls_card_cd, string ls_paymnt_dt)
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("ls_card_cd", typeof(string), ls_card_cd);
			lo_dp.AddProperty("ls_paymnt_dt", typeof(string), ls_paymnt_dt);
			lo_dp.AddProperty("ls_user_id", typeof(string), USER_ID);

			using (Crd2010r_RT _Crd2010r_RT = new Crd2010r_RT())
			{
				int li_return = _Crd2010r_RT.ConfirmProcess(lo_dp);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_008" : "MSG_ERR_106";	//확정되었습니다:확정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);	// 확정되었습니다
			}
		}

		//저장
		private void InsertProcess()
		{
			try
			{
				using (Crd1012m_RT _Crd1012m_RT = new Crd1012m_RT())
				{
					int li_return = _Crd1012m_RT.InsertXmlProcess(SetValue());
					string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
					CallMsgBoxInAjax(ls_msg_id);

					SearchProcess();
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}
		
		//검색
		private void SearchProcess()
		{
			SetSearchParameter();
			SelectProcess();
		}

		#endregion

		#region SetValue

		//SetValue
		private string SetValue()
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			//루프를 돌면서 선택된 데이터만 XML로 만듬
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				HtmlInputCheckBox cb_select = (HtmlInputCheckBox)GridView1.Rows[i].FindControl("cb_check_card");

				string ls_biz_dt = GridView1.Rows[i].Cells[1].Text.Replace('.', '-').Replace('/', '-').Trim();	//Biz_Dt
				string ls_div = GridView1.Rows[i].Cells[2].Text.Trim();	//Div
				LinkButton lbtn_rc = (LinkButton)GridView1.Rows[i].FindControl("lbtn_rc");	//Contents
				string ls_contents = lbtn_rc.Text.Trim();
				string ls_amount = GridView1.Rows[i].Cells[4].Text.Trim();	//Amount
				string ls_remark = lbtn_rc.Text.Trim();
				string ls_biz_div = "";
				
				switch (ls_div)
				{
					case "일시불":
						ls_biz_div = "AB001";
						break;
					case "현금서비스":
						ls_biz_div = "AB002";
						break;
					case "할부":
						ls_biz_div = "AB003";
						break;
					default :
						ls_biz_div = "AB001";
						break;
				}

				//내용에 버스,지하철,택시가 있으면 '교통숙박비(AC010)'계정으로 저장, 나머지는 기타(통계미반영)으로
				string ls_account = "AC997"; //기타(통계미반영)
				if (ls_contents.Contains("버스"))
				{
					ls_account = "AC010";
					ls_contents = "버스이용료";
				}

				if (ls_contents.Contains("지하철"))
				{
					ls_account = "AC010";
					ls_contents = "지하철이용료";
				}

				if (ls_contents.Contains("택시"))
				{
					ls_account = "AC010";
					ls_contents = "택시비";
				}

				if (cb_select.Checked && ls_biz_div != "AB003")
				{
					sb.Append("<UPDMS_CRD_ITEM_BIZ>");
					sb.Append("<Card_Cd>" + kw1 + "</Card_Cd>");
					sb.Append("<Biz_Div>" + ls_biz_div + "</Biz_Div>");
					sb.Append("<Account>" + ls_account + "</Account>");
					sb.Append("<Contents><![CDATA[" + ls_contents + "]]></Contents>");
					sb.Append("<Amount>" + ConversionUtil.ExtractNumberInt(ls_amount) + "</Amount>");
					sb.Append("<Biz_Dt>" + ls_biz_dt + "</Biz_Dt>");
					sb.Append("<Paymnt_Dt>" + lbl_paymnt_dt.Text + "</Paymnt_Dt>");
					sb.Append("<Remark><![CDATA[" + ls_remark + "]]></Remark>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("</UPDMS_CRD_ITEM_BIZ>");
				}
			}

			sb.Append("</UPDMS>");

			//Base.AppFramework.SMEventLog.WriteDataLog("Crd4010b.SetValue()", sb.ToString());

			return sb.ToString();
		}

		#endregion

		#region CheckData, CheckBalanceAmount

		//체크
		private void CheckData()
		{
			try
			{
				//내용클릭시 날짜와 금액으로 UPDMS_DATA체크하여 있으면 체크박스 체크
				for (int i = 0; i < GridView1.Rows.Count; i++)
				{
					string card_biz_dt = GridView1.Rows[i].Cells[1].Text.Replace('.', '-').Replace('/', '-');
					string card_amount = GridView1.Rows[i].Cells[4].Text;

					for (int j = 0; j < GridView2.Rows.Count; j++)
					{
						string updms_biz_dt = GridView2.Rows[j].Cells[1].Text;
						string updms_amount = GridView2.Rows[j].Cells[4].Text;

						if (card_biz_dt == updms_biz_dt && card_amount == updms_amount)
						{
							//HtmlInputCheckBox cb_updms = (HtmlInputCheckBox)GridView2.Rows[j].Cells[0].FindControl("cb_check_updms");
							//cb_updms.Checked = true;
							GridView2.Rows[j].Attributes.Add("class", "bg_bluesky");

							//HtmlInputCheckBox cb_card = (HtmlInputCheckBox)GridView1.Rows[i].Cells[0].FindControl("cb_check_card");
							//cb_card.Checked = true;
							GridView1.Rows[i].Attributes.Add("class", "bg_bluesky");
						}
					}
				}
			}
			catch(Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}

		//차액 계산
		private void CheckBalanceAmount()
		{
			decimal ld_card = Convert.ToDecimal(GridView1.FooterRow.Cells[4].Text);
			decimal ld_updms = Convert.ToDecimal(GridView2.FooterRow.Cells[4].Text);
			ibtn_confirm.Attributes.Remove("onclick");

			lbl_balance_amount.Text = (ld_card - ld_updms).ToString("#,###,##0");

			if ((ld_card - ld_updms) == 0)
			{
				ibtn_confirm.Attributes.Add("title", GetXmlMsg("STR_004"));//확정할 수 있습니다
				ibtn_confirm.Attributes.Add("onclick", "return chkConfirm('" + lbl_card_nm.Text + "','" + lbl_paymnt_dt.Text + "')");
			}
			else
			{
				ibtn_confirm.Attributes.Add("title", GetXmlMsg("STR_017"));//확정할 수 없습니다
				ibtn_confirm.Attributes.Add("onclick", "msgBox.alert(getMsg(MSG_ERR_174));return false;");	//차액이 맞지 않습니다
			}
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					ibtn_search.Visible = FileUtil.IsFileExist(gs_source) ? true : false;
					ibtn_save.Visible = false;
					ibtn_verify.Visible = false;
					ibtn_confirm.Visible = false;
					table_list_set.Visible = false;
					table_detail_1.Visible = false;
					break;
				case "R":	// 검색버튼 클릭후 엑셀데이터 있을때
					ibtn_search.Visible = true;
					ibtn_save.Visible = true;
					ibtn_verify.Visible = true;
					ibtn_confirm.Visible = true;
					table_list_set.Visible = true;
					table_detail_1.Visible = true;
					break;
				case "N":	// 검색버튼 클릭후 엑셀데이터 없을때
					ibtn_search.Visible = true;
					ibtn_save.Visible = false;
					ibtn_verify.Visible = false;
					ibtn_confirm.Visible = false;
					table_list_set.Visible = false;
					table_detail_1.Visible = false;
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region File (UploadFile)

		//UploadFile
		private void UploadFile()
		{
			string ls_file_name = "";
			string upload_path = FILE_PATH_UPLOAD_EXCEL_BATCH;

			HttpFileCollection hfc = Request.Files;
			for (int i = 0; i < hfc.Count; i++)
			{
				HttpPostedFile hpf = hfc[i];
				if (hpf.ContentLength > 0)
				{
					ls_file_name = ls_file_name + Path.GetFileName(hpf.FileName);	//업로드시 선택한 파일명
					string ls_save_path = upload_path + ls_file_name; //저장경로

					//Crd4010b_template.xls만 업로드 가능
					if (ls_file_name == PID + "_template.xls")
					{
						//파일저장
						hpf.SaveAs(ls_save_path);
					}
					else
					{
						CallMsgBoxInAjax("MSG_ERR_196");	//템플릿 파일이 아닙니다
					}
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_126");	//템플릿 파일이 없습니다
				}
			}
		}		

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//페이지별 합계
				if (DataBinder.Eval(e.Row.DataItem, "Amount") != null && DataBinder.Eval(e.Row.DataItem, "Amount").ToString() != "")
				{
					ld_amount_card += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
				}
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 4;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Text = ld_amount_card.ToString("#,###,##0");
				e.Row.Cells[4].Attributes.Add("class", "money");
			}

			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 2);
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			//내용클릭시 날짜와 금액으로 UPDMS_DATA체크하여 있으면 체크박스 체크
			string card_biz_dt = row.Cells[1].Text.Replace('.', '-').Replace('/', '-');
			string card_amount = row.Cells[4].Text;

			for (int i = 0; i < GridView2.Rows.Count; i++)
			{
				string updms_biz_dt = GridView2.Rows[i].Cells[1].Text;
				string updms_amount = GridView2.Rows[i].Cells[4].Text;

				if (card_biz_dt == updms_biz_dt && card_amount == updms_amount)
				{
					HtmlInputCheckBox cb_updms = (HtmlInputCheckBox)GridView2.Rows[i].Cells[0].FindControl("cb_check_updms");
					cb_updms.Checked = true;
					GridView2.Rows[i].Attributes.Add("class", "bg_bluesky");

					HtmlInputCheckBox cb_card = (HtmlInputCheckBox)row.Cells[0].FindControl("cb_check_card");
					cb_card.Checked = true;
					row.Attributes.Add("class", "bg_bluesky");
				}
			}
			gs_page_mode = "R";
		}

		//RowDataBound
		protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				string ls_mass_link = "<a href=\"javascript:void(0);\" onclick=\"goCardMassPage('" + global.GetDirDepth("Crd1012m") + "','" + kw1 + "','" + gv.DataKeys[e.Row.RowIndex].Values["Account"].ToString() + "','" + e.Row.Cells[1].Text + "','" + e.Row.Cells[1].Text + "','" + e.Row.Cells[3].Text + "','P');\">" + e.Row.Cells[3].Text + "</a>";
				string ls_ins_link = "<a href=\"javascript:void(0);\" onclick=\"goCardInsPage('" + global.GetDirDepth("Crd1013m") + "','" + kw1 + "','" + gv.DataKeys[e.Row.RowIndex].Values["Account"].ToString() + "','" + e.Row.Cells[1].Text + "','" + e.Row.Cells[1].Text + "','P');\">" + e.Row.Cells[3].Text + "</a>";

				switch (e.Row.Cells[2].Text)
				{
					case "일시불" :
						e.Row.Cells[3].Text = ls_mass_link;
						break;
					case "할부":
						e.Row.Cells[3].Text = ls_ins_link;
						break;
					default:
						break;
				}

				//합계
				ld_amount_updms += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 4;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Text = ld_amount_updms.ToString("#,###,##0");
				e.Row.Cells[4].Attributes.Add("class", "money");
			}

			SMGridView sGv = new SMGridView(this.Page, ref GridView2);
			sGv.RowSpanGridView(GridView2, 2);
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();

			//먼저 확정불가처리한 후
			ibtn_confirm.Attributes.Remove("onclick");
			ibtn_confirm.Attributes.Add("title", GetXmlMsg("STR_018"));//먼저 검증을 실행하세요
			ibtn_confirm.Attributes.Add("onclick", "msgBox.alert(getMsg(MSG_ERR_173));return false;");//먼저 검증을 실행하세요
		}

		//검증
		protected void ibtn_verify_Click(object sender, EventArgs e)
		{
			gs_page_mode = "R";
			CheckData();
			CheckBalanceAmount();
		}
		
		//업로드
		protected void ibtn_upload_Click(object sender, EventArgs e)
		{
			UploadFile();
		}

		//확정
		protected void ibtn_confirm_Click(object sender, EventArgs e)
		{
			SetSearchParameter();
			ConfirmProcess(kw1, kw2);
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			SetSearchParameter();
			InsertProcess();
		}

		#endregion
	}
}
